//
//  ViewController.m
//  flutterTest
//
//  Created by lvfeijun on 2022/3/2.
//

#import "ViewController.h"
#import <Flutter/FlutterViewController.h>
#import <Flutter/Flutter.h>
#import <flutter_boost/FlutterBoost.h>

@interface HomeScroller : UIScrollView

@end

@implementation HomeScroller

-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    if (self.contentOffset.x == self.frame.size.width) { return false;  }
    return true;
}

@end

@interface ViewController ()
{
    UIScrollView * scrView;
    FlutterViewController * ft;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:CGRectMake(100, 100, 200, 50)];
    [button setBackgroundColor:[UIColor greenColor]];
    [button setTitle:@"ClickMePushToFlutterVC" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(btn_click) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    return;
    
    scrView = HomeScroller.new;
    scrView.showsHorizontalScrollIndicator = false;
    scrView.bounces = false;
    scrView.pagingEnabled = true;
    scrView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    [self.view addSubview:scrView];
    
    CGFloat sw = self.view.frame.size.width;
    
    scrView.contentSize = CGSizeMake(sw*2, 0);
    
    
    UIView * redView = UIView.new;
    redView.frame = CGRectMake(0, 0, sw, self.view.frame.size.height);
    redView.backgroundColor = UIColor.redColor;
    [scrView addSubview:redView];
    
    CGFloat stateH = 20;
    CGFloat botH = 0;
    if (@available(iOS 11.0, *)) {
        stateH = MAX(UIApplication.sharedApplication.keyWindow.safeAreaInsets.top, 20);
        botH = UIApplication.sharedApplication.keyWindow.safeAreaInsets.bottom;
    }
    
    CGFloat defH = self.view.frame.size.height-44-49-stateH-botH;
    
    ft = [[FlutterViewController alloc] initWithProject:nil nibName:nil bundle:nil];
    ft.view.backgroundColor = UIColor.clearColor;
    ft.view.frame = CGRectMake(sw, 0, sw, defH);
    [self addChildViewController:ft];
    [scrView addSubview:ft.view];
    
    UISwipeGestureRecognizer * swguest = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeAction:)];
    swguest.direction = UISwipeGestureRecognizerDirectionRight;
    [ft.view addGestureRecognizer:swguest];
        
    __weak FlutterViewController * wft = ft;
    __weak ViewController * ws = self;
    __weak UIScrollView * wscr = scrView;
    FlutterMethodChannel * channnel = [FlutterMethodChannel methodChannelWithName:@"updateScreen" binaryMessenger:(NSObject<FlutterBinaryMessenger>*)ft];
    [channnel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {
        NSString * res = call.arguments;
        NSLog(@"updateScreen %@", call.method);
        if ([call.method isEqualToString:@"change"]) {
            BOOL isfull = [res isEqualToString:@"full"];
            CGFloat wh = wft.view.frame.size.height;
            if (isfull && wh != UIScreen.mainScreen.bounds.size.height) {
                wft.view.frame = UIScreen.mainScreen.bounds;
                [ws.tabBarController.view addSubview:wft.view];
            }else if (!isfull && wh != defH){
                wft.view.frame = CGRectMake(sw, 0, ws.view.frame.size.width, defH);
                [wscr addSubview:wft.view];
            }
        }
    }];
    
    FlutterMethodChannel * envC = [FlutterMethodChannel methodChannelWithName:@"env" binaryMessenger:(NSObject<FlutterBinaryMessenger>*)ft];
    [envC invokeMethod:@"env" arguments:@{@"env":@1}];
    
    // 文件
    {
        FlutterMethodChannel * channnel = [FlutterMethodChannel methodChannelWithName:@"Filep" binaryMessenger:(NSObject<FlutterBinaryMessenger>*)ft];
        [channnel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {
            NSDictionary * res = call.arguments;
            NSString * method = call.method;
//            TRDModel * model = [TRDModel downLoad:@"xwl" name:res[@"name"] uname:@"徐***" url:res[@"url"]];
//            if ([method isEqualToString:@"preview"]) {
//                [model open:self];
//            }
//            else if ([method isEqualToString:@"download"]) {
//
//            }
//            result(@[@(model.state==TRDModel_State_s)]);
        }];
    }
    
    // 传输列表
    {
        FlutterMethodChannel * channnel = [FlutterMethodChannel methodChannelWithName:@"gotransmit" binaryMessenger:(NSObject<FlutterBinaryMessenger>*)ft];
        [channnel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {
//            TransmitViewController * transmit = [TransmitViewController push:call.arguments from:self];
            
            NSLog(@"gotransmit");
//            TRUModel * model = TRUModel.new;
//            model.delgate = self;
//            model.name = @"233.ppt";
//            TRUModel * model2 = TRUModel.new;
//            model2.name = @"23345.ai";
//
//
//            [transmit configUpload:@[model,model2]];
        }];
    }
    
//    [wft.binaryMessenger sendOnChannel:@"env" message:data];

}

- (void)btn_click1
{
    [self btn_click:@"route1"];
}
- (void)btn_click2
{
    [self btn_click:@"route2"];
}
- (void)btn_click3
{
    [self btn_click:@"splash"];
}
- (void)btn_click4
{
    [self btn_click:@"otherPage"];
}
- (void)btn_click:(NSString *)route
{
    [self jumpToFlutterBoost:route];
    return;
    
    [self.navigationController pushViewController:self.flutterV animated:YES];
    
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    FlutterEngine *flutterEngine = appDelegate.flutterEngine;
    
    NSString *router = @"";
    if ([route isEqualToString:@"splash"]) {
//        router = @"/login";
        router = @"login_page.dart";
        
    } else if([route isEqualToString:@"otherPage"]){
//        router = @"/login/register";
        router = @"register_page.dart";
        
    } else if([route isEqualToString:@"route1"]){
//        router = @"/login/smsLogin";
        router = @"login/page/reset_password_page.dart";
        
    } else if([route isEqualToString:@"route2"]){
//        router = @"/login/resetPassword";
        router = @"sms_login_page.dart";
    }
//    [flutterEngine runWithEntrypoint:nil initialRoute:router];
    [flutterEngine runWithEntrypoint:@"my flutter engine" libraryURI:router];
}

-(void)jumpToFlutterBoost:(NSString *)route
{
    ///引擎初始化的时候会有引导页？？？
    if ([route isEqualToString:@"splash"]||[route isEqualToString:@"otherPage"]) {
        ///引擎必须提前初始化,解决（1）（2）问题
        FlutterBoostRouteOptions* options = [[FlutterBoostRouteOptions alloc]init];
        options.pageName = route;
        if ([route isEqualToString:@"splash"]) {
            options.arguments = @{@"present":@(YES)};
        } else
        {
            options.arguments = @{@"animated":@(YES)};
        }
       
        //页面是否透明（用于透明弹窗场景），若不设置，默认情况下为true
        options.opaque = true;
        //这个是push操作完成的回调，而不是页面关闭的回调！！！！
        options.completion = ^(BOOL completion) {
            DDLogDebug(@"completion:%ld",completion);
        };
        //这个是页面关闭并且返回数据的回调，回调实际需要根据您的Delegate中的popRoute来调用
        options.onPageFinished = ^(NSDictionary *dic) {
            DDLogDebug(@"onPageFinished:%@",dic);
        };

        [[FlutterBoost instance]open:options];
    } else if([route isEqualToString:@"route1"]){
        //用FlutterBoost没有设置上，只是用了默认的
        /// 引擎不能提前初始化，用push每次都有欢迎页
        FlutterViewController *flutterViewController = [[FlutterViewController alloc]initWithProject:nil initialRoute:@"/route1" nibName:nil bundle:nil];
//        [flutterViewController setInitialRoute:route];
        [[HQTabBarRootViewController currentWidowsViewController].navigationController pushViewController:flutterViewController animated:YES];
    } else if([route isEqualToString:@"route2"]){
        //用FlutterBoost没有设置上，只是用了默认的
        /// 引擎必须提前初始化，用prese每次都会卡一下
        FlutterViewController *flutterViewController = [[FlutterViewController alloc]initWithProject:nil initialRoute:@"/route2" nibName:nil bundle:nil];
//        FlutterViewController *flutterViewController = [[FlutterViewController alloc]init];
//        [flutterViewController setInitialRoute:route];
        //只要是全屏就会有欢迎页
//        flutterViewController.modalPresentationStyle = UIModalPresentationOverFullScreen;
        [[HQTabBarRootViewController currentWidowsViewController] presentViewController:flutterViewController animated:YES completion:nil];
    }
}

- (FlutterViewController *)flutterV
{
    if (!_flutterV) {
        _flutterV = [[FlutterViewController alloc]init];
    }
    return _flutterV;
}


//-(void)startUpload:(TRUModel *)mode
//{
////    NSLog(@"开始上传 %@",mode.name);
//}
//
//-(void)stopUpload:(TRUModel *)mode
//{
////    NSLog(@"暂停上传 %@",mode.name);
//}
//
//-(void)delUpload:(TRUModel *)mode
//{
////    NSLog(@"删除上传 %@",mode.name);
//}


-(void)swipeAction:(UISwipeGestureRecognizer *)guest{
    if (scrView.contentOffset.x!=self.view.frame.size.width || ft.view.frame.size.height == UIScreen.mainScreen.bounds.size.height) {  return;  }
    [UIView animateWithDuration:0.3 animations:^{
        self->scrView.contentOffset = CGPointMake(0, self->scrView.contentOffset.y);
    }];
}


- (void)btn_click {
    
//    FlutterViewController *flutterViewController = [[FlutterViewController alloc] init];
    FlutterViewController *flutterViewController = [[FlutterViewController alloc] initWithProject:nil nibName:nil bundle:nil];
    if (self.navigationController) {
        [self.navigationController pushViewController:flutterViewController animated:YES];
    } else {
        [self presentViewController:flutterViewController animated:YES completion:nil];
    }
    
    
    /* 方式 2
     
    FlutterViewController *fluvc = [[FlutterViewController alloc]init];
    [self addChildViewController:fluvc];
    fluvc.view.frame = self.view.bounds;
    [fluvc didMoveToParentViewController:self];
    [self.view addSubview:fluvc.view];
    [self.navigationController pushViewController:fluvc animated:YES];
     
     */
}

@end
